<?php

/*
 * Copyright 2008 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#namespace tehframework\mvc\annotations;

#use tehframework\annotations\DocBlockFactory;

class RendererScanner
{
	/**
	 * @var DocBlockFactory
	 */
	protected $docBlockFactory;
	
	/**
	 * @param  DocBlockFactory $docBlockFactory
	 */
	public function __construct(DocBlockFactory $docBlockFactory)
	{
		$this->docBlockFactory = $docBlockFactory;
	}
	
	/**
	 * @param  RecursiveDirectoryIterator $directory
	 * @param  string? $ns
	 * @return RendererAnnotation[]
	 * @throws ReflectionException
	 */
	public function scanForRenderers(
		RecursiveDirectoryIterator $directory, $ns = null)
	{
		$renderers = array();
		
		/* @var $entry SplFileInfo */
		foreach ($directory as $entry)
		{
			if ($entry->isDir())
			{
				$renderers = array_merge($renderers,
					$this->scanForRenderers($directory->getChildren(),
						$ns . T_NS_SEPARATOR . $entry->getFilename()));
			}
			elseif ($this->isViewFile($entry->getFilename()))
			{
				$renderers = array_merge($renderers,
					$this->resolveRenderers($entry, $ns));
			}
		}
		
		return $renderers;
	}
	
	/**
	 * @param  string $filename
	 * @return bool
	 */
	protected function isViewFile($filename)
	{
		return substr($filename, -8) === 'View.php';
	}
	
	/**
	 * @param  SplFileInfo $file
	 * @param  string? $ns
	 * @return RendererAnnotation[]
	 * @throws ReflectionException
	 */
	protected function resolveRenderers(SplFileInfo $file, $ns)
	{
		include_once $file->getPathname();
		
		$class = new ReflectionClass(
			(empty($ns) ? '' : $ns . '::') . substr($file->getFilename(), 0, -4)
		);
		
		$renderers = array();
		
		/* @var $method ReflectionMethod */
		foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method)
		{
			$docBlock = $this->docBlockFactory->getDocBlock($method);
			
			if ($docBlock->isAnnotatedWith('Renderer'))
			{
				$renderers[] = $docBlock->getAnnotation('Renderer');
			}
		}
		
		return $renderers;
	}
}